# Setup ----
## Load and install packages
packages <- c("tidyverse","haven","lubridate","janitor","readxl",
              "stringr","textclean","repmis","pander","qualtRics","sjlabelled",
              "tidymodels","jtools","estimatr","huxtable",
              "ordinal","srvyr","ggstatsplot","broom.mixed",
              "flextable","compareGroups","skimr",
              "magrittr","ggridges","ggpubr","ggstance","ggdark",
              "hrbrthemes","viridis","extrafont",
              "cregg","conjoint","cjoint",
              "dabestr","patchwork") 

installed_packages <- packages %in% 
  rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}
invisible(lapply(packages, library, character.only = TRUE))

## Change wd
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
rm(list=ls())
gc()


## Load data, colors and themes
loadfonts()
load("data_col_font_covidbr.RData")


# FIGURE 1 ----
p1 <- df_join %>% 
  mutate(isola_dummy=factor(case_when(
    isolamento >3 ~ 3,
    isolamento == 3 ~ 2,
    isolamento <3 ~ 1),
    levels = c(1,2,3),
    labels=c("Disagree","Indifferent","Agree"),
    ordered = T)) %>%
  group_by(Rnd,ideologia_cat,isola_dummy) %>%
  summarise(n=n()) %>%
  group_by(Rnd,ideologia_cat) %>%
  mutate(prop=prop.table(n)) %>%
  arrange(Rnd,ideologia_cat,desc(isola_dummy)) %>%
  mutate(lab_pos = cumsum(prop) - 0.5 * prop) %>%
  ggplot(aes(x=prop,fill=isola_dummy,y=Rnd)) +
  geom_bar(alpha=.75,stat = "identity",position = "stack") +
  geom_text(data=. %>% dplyr::filter(prop>0.1),
            aes(x=lab_pos,label=paste0(round(100*prop,0),"%")),
            size=3,fontface="bold",color="white") +
  scale_fill_manual(values = c("indianred3","grey50","dodgerblue4")) +
  scale_x_continuous(labels=scales::percent) +
  coord_cartesian(clip = "off",
                  expand = T) + 
  labs(x="",y="",fill="",title="Social Distancing Policy") +
  theme_ipsum_mod +
#  theme_minimal() +
  facet_wrap(~ideologia_cat,ncol = 1) +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t),
        plot.subtitle= element_text(family = fonte_t),
        title = element_text(family = fonte_t),
        strip.text = element_text(family = fonte_t),
        legend.position = "bottom",
        legend.key.height =unit(.75,"line"),
        panel.spacing=grid::unit(.25, "lines"))


p2 <- df_join %>% 
  mutate(isola_dummy=factor(case_when(
    bolsonaro >3 ~ 3,
    bolsonaro == 3 ~ 2,
    bolsonaro <3 ~ 1),
    levels = c(1,2,3),
    labels=c("Negative","Neutral","Positive"),
    ordered = T)) %>%
  group_by(Rnd,ideologia_cat,isola_dummy) %>%
  summarise(n=n()) %>%
  group_by(Rnd,ideologia_cat) %>%
  mutate(prop=prop.table(n)) %>%
  arrange(Rnd,ideologia_cat,desc(isola_dummy)) %>%
  mutate(lab_pos = cumsum(prop) - 0.5 * prop) %>%
  ggplot(aes(x=prop,fill=isola_dummy,y=Rnd)) +
  geom_bar(alpha=.75,stat = "identity",position = "stack") +
  geom_text(data=. %>% dplyr::filter(prop>0.1),
            aes(x=lab_pos,label=paste0(round(100*prop,0),"%")),
            size=3,fontface="bold",color="white") +
  scale_fill_manual(values = c("indianred3","grey50","dodgerblue4")) +
  scale_x_continuous(labels=scales::percent) +
  coord_cartesian(clip = "off",
                  expand = T) + 
  labs(x="",y="",fill="",title="President's evaluation") +
  theme_ipsum_mod +
  #  theme_minimal() +
  facet_wrap(~ideologia_cat,ncol = 1) +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t),
        plot.subtitle= element_text(family = fonte_t),
        title = element_text(family = fonte_t),
        strip.text = element_text(family = fonte_t),
        legend.position = "bottom",
        legend.key.height =unit(.75,"line"),
        panel.spacing=grid::unit(.25, "lines"))


### generating png
compara_ondas_fig <- p1 + p2 
compara_ondas_fig
ggsave("fig1.png",plot=compara_ondas_fig,dpi=320,width = 30, height = 15, units = "cm")




# Conjoint analisys ----

df.conjoint <- df2 %>%
  dplyr::select(ResponseId,QID200_NPS_GROUP:Q94,-contains("_GROUP"))


conjoint.labels <- data.frame(label=sjlabelled::get_label(df.conjoint)) %>%
  mutate(var=rownames(.)) %>% dplyr::select(-label) %>% 
  left_join(labels) %>%
  mutate(lab.simp=mgsub(label,
                        c("Como você avaliaria o candidato ",
                          " em uma escala de 1 (definitivamente NÃO VOTARIA) a 10 (definitivamente VOTARIA)?",
                          "Se você tivesse que escolher entre esses dois candidatos para presidente quem você escolheria?"),
                        c('',"","pick")))


names(df.conjoint) <- c("ResponseId",
                        paste0(rep(c("rat_","rat_","pick_"),8),
                               c("1","2","1",
                                 "3","4","2",
                                 "5","6","3",
                                 "7","8","4",
                                 "4","3","2",
                                 "2","1","1",
                                 "6","5","3",
                                 "8","7","4"),
                             c(rep("a",12),rep("b",12))))


conjoint.labels$newnames <- names(df.conjoint)



con_test <- df.conjoint %>%
  transmute( ResponseId = ResponseId,
             
             pick1 = ifelse(is.na(pick_1a)==T,
                           as.character(pick_1b),
                           as.character(pick_1a)),
            pick1 = factor(pick1,ordered = F),
            rt1=ifelse(is.na(rat_1a)==T,rat_1b,rat_1a), #Feitosa
            rt1 = as.numeric(rt1),
            rt2=ifelse(is.na(rat_2a)==T,rat_2b,rat_2a), #Soares
            rt2 = as.numeric(rt2),
            
            pick2 = ifelse(is.na(pick_2a)==T,
                           as.character(pick_2b),
                           as.character(pick_2a)),
            pick2 = factor(pick2,ordered = F),
            rt3=ifelse(is.na(rat_3a)==T,rat_3b,rat_3a), #Garcia
            rt3 = as.numeric(rt3),
            rt4=ifelse(is.na(rat_4a)==T,rat_4b,rat_4a), #Torres
            rt4 = as.numeric(rt4),
            
            pick3 = ifelse(is.na(pick_3a)==T,
                           as.character(pick_3b),
                           as.character(pick_3a)),
            pick3 = factor(pick3,ordered = F),
            rt5=ifelse(is.na(rat_5a)==T,rat_5b,rat_5a), #Lessa
            rt5 = as.numeric(rt5),
            rt6=ifelse(is.na(rat_6a)==T,rat_6b,rat_6a), #Galvão
            rt6 = as.numeric(rt6),
            
            pick4 = ifelse(is.na(pick_4a)==T,
                           as.character(pick_4b),
                           as.character(pick_4a)),
            pick4 = factor(pick4,ordered = F),
            rt7=ifelse(is.na(rat_7a)==T,rat_7b,rat_7a), #Aguiar
            rt7 = as.numeric(rt7),
            rt8=ifelse(is.na(rat_8a)==T,rat_8b,rat_8a), #Medeiros
            rt8 = as.numeric(rt8)
            
  ) %>%
  rowwise() %>%
  mutate(zerador = sd(c(rt1,rt2,rt3,rt4,rt5,rt6,rt7,rt8))) %>% 
  ungroup() %>%
  dplyr::filter(zerador>0) %>% dplyr::select(-zerador)

## Utilities
preferences <- con_test %>% #ratings matrix
  dplyr::select(-contains("pick")) %>% 
  left_join(df2 %>% 
              dplyr::select(ResponseId,
                            isolamento,
                            bolsonaro,
                            voto_bolsonaro,
                            voto_bolsonaro_grupo,
                            covid,
                            covid_n,
                            medo,
                            medo_cat,
                            econ_loss_cat,
                            econ_loss,
                            econ_loss_d,
                            ideologia,
                            ideologia_cat,
                            religiao,
                            evangelico,
                            demog_tp)) %>%
  drop_na() %>%
  data.frame()



# Níveis dos atributos
levelnames=data.frame(levels=c("Corruption",
                               "Social",
                               "Antiparty",
                               "Proparty",
                               "Conservative",
                               "Liberal",
                               "Market_oriented",
                               "State_oriented"))



# Utilizando conjoint como preditora
conjoint::caPartUtilities(y=preferences[,2:9],x=profiles,z=levelnames)[,c(2,4,6,8)] %>%
  data.frame() %>%
  mutate(Total = abs(Corruption) + abs(Antiparty) + abs(Conservative) + abs(Market_oriented),
         Issue=abs(Corruption*100)/Total,
         Parties=abs(Antiparty*100)/Total,
         Values=abs(Conservative*100)/Total,
         EconPol=abs(Market_oriented*100)/Total,
         Values_valencia=ifelse(Conservative<0,"Liberal","Conservative"),
         Perfil=ifelse(Values>EconPol,"Identitarian","Pragmatic"),
         Perfil_completo = factor(paste(Values_valencia,Perfil))) -> conjoint_cargas

conjoint_cargas %<>%
  rowwise() %>%
  mutate(dimensao_principal=case_when(
         max(Values,EconPol,Issue,Parties)==Values ~ "Values",
         max(Values,EconPol,Issue,Parties)==EconPol ~ "EconPol",
         max(Values,EconPol,Issue,Parties)==Issue ~ "Issue",
         max(Values,EconPol,Issue,Parties)==Parties ~ "Parties")
) %>%
  ungroup()

preferences_cargas <- bind_cols(preferences,conjoint_cargas)


# Models conjoint ----


tt <- preferences_cargas %>%
  dplyr::filter(ideologia>3) %>%
  mutate()

Tt <- TukeyHSD(aov(tt$isolamento ~ tt$dimensao_principal))
Tt$`tt$dimensao_principal` %>% 
  as.data.frame() %>% rownames_to_column() %>%
  mutate(rowname = gsub("\n","",rowname)) %>%
  knitr::kable(col.names = c("","Dif.","Lim inf","Lim sup","p-valor"),
               digits=3,format = "markdown")


tt <- preferences_cargas %>%
  dplyr::filter(ideologia>3) %>%
  mutate()

Tt <- TukeyHSD(aov(tt$bolsonaro ~ tt$dimensao_principal))
Tt$`tt$dimensao_principal` %>% 
  as.data.frame() %>% rownames_to_column() %>%
  mutate(rowname = gsub("\n","",rowname)) %>%
  knitr::kable(col.names = c("","Dif.","Lim inf","Lim sup","p-valor"),
               digits=3,format = "markdown")

# FIGURE 2 ----

# Fear of death, social distancing and profiles


# Bozo's evaluation
pref_bolsobom <-preferences %>% 
  dplyr::filter(ideologia>3,
                bolsonaro > 3
  ) %>%
  dplyr::select(rt1:rt8)

pref_bolsoruim <-preferences %>% 
  dplyr::filter(ideologia>3,
                bolsonaro < 3
  ) %>%
  dplyr::select(rt1:rt8)

importancia <-
  bind_cols(
    data.frame(Bolsonaro_app = conjoint::caImportance(y=pref_bolsobom,x=profiles)), 
    data.frame(Bolsonaro_disapp = conjoint::caImportance(y=pref_bolsoruim,x=profiles))
  ) %>% mutate(dim=c("Issue","Parties","Values","EconPol")) %>%
  pivot_longer(-dim)


barras_importancia <-
  importancia %>%
  ggplot(aes(x=dim,y=value,fill=name,color=name)) +
  geom_bar(color=NA,aes(alpha=paste(dim,name)),stat = "identity") +
  geom_text(fontface="bold",family = fonte_t,
            size=4,vjust=-.5,aes(label=paste0(round(value,1),"%"))) +
  facet_grid(name~dim,scales = "free",switch = "x",
             labeller = labeller(name = c("Bolsonaro_disapp"="Disapprove",
                                          "Bolsonaro_app"="Approve"))) +
  labs(x="",y="",title="A. Bolsonaro's performance") +
  coord_cartesian(clip = "on",ylim = c(0,40),expand = F) + 
  scale_alpha_manual(values = c(.5,.8,.5,.5,
                                
                                .5,.5,.8,.5)) +
  scale_fill_manual(values = c("dodgerblue4","indianred4")) +
  scale_color_manual(values = c("dodgerblue4","indianred4")) +
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        legend.position = "none",
        strip.text.y = element_text(size=12,face = "bold",hjust = .5,family = fonte_t),
        strip.text.x =  element_text(size=11,hjust = .5,family = fonte_t),
        
        plot.title= element_text(family = fonte_t,size=12),
        plot.subtitle= element_text(family = fonte_t),
        #  title = element_text(family = fonte_t),
        plot.caption = element_text(family = fonte_t),
        axis.text = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),)


m1 <- conjoint::caPartUtilities(y=pref_bolsobom,x=profiles,z=levelnames)

m2 <- conjoint::caPartUtilities(y=pref_bolsoruim,x=profiles,z=levelnames)

lab.graf.b <- data.frame(dim=c("EconPol",
                               "Issue",
                               "Values",
                               "Parties"),
                         valor_esq=rep(c(-2),4),
                         valencia_esq=c("+ State oriented",
                                        "+ Social policies",
                                        "+ Liberal",
                                        "+ Proparty"),
                         valor_dir=rep(c(2),4),
                         valencia_dir=c("+ Market oriented",
                                        "+ Anticorruption",
                                        "+ Conservative",
                                        "+ Antiparty"))



m1m2 <- m1 %>% data.frame() %>% mutate(Perfil="Bolsonaro_bem") %>%
  bind_rows(m2 %>% data.frame() %>% mutate(Perfil="Bolsonaro_mal")) %>%
  
  dplyr::select(-intercept) %>%
  pivot_longer(1:8) %>%
  mutate(
    dim = case_when(
      name %in% c("Corruption",
                  "Social") ~ "Issue",    
      name %in% c("Antiparty",
                  "Proparty") ~  "Parties", 
      name %in% c("Conservative",
                  "Liberal") ~  "Values", 
      name %in% c("Market_oriented",
                  "State_oriented") ~     "EconPol"
    ),
    ordem = case_when(
      name == "Corruption"~1,
      name == "Social"~2,
      name == "Antiparty"~1,
      name == "Proparty"~2,
      name == "Conservative"~1,
      name == "Liberal"~2,
      name == "Market_oriented"~1,
      name == "State_oriented"~2
    )
  ) %>%
  dplyr::filter(ordem==1) %>%
  left_join(lab.graf.b)

valencias_conjoint <-
  m1m2 %>%
  dplyr::filter(dim %in% c("Values","EconPol")) %>%
  ggplot(aes(x=name,y=value,color=Perfil)) +
  stat_summary(fun = mean, 
               geom = "point",
               position = position_dodge(width = 0.4)) + 
  
  stat_summary(fun.data = mean_cl_boot,  
               geom = "errorbar", width = 0.4,
               position = position_dodge()) +
  geom_hline(yintercept = 0,linetype=2) +
  geom_text(aes(y=valor_esq,label=valencia_esq),
            color="black",family = fonte_t,
            size=3.5,check_overlap = T) +
  geom_text(aes(y=valor_dir,label=valencia_dir),
            color="black",family = fonte_t,
            size=3.5,check_overlap = T) +
  facet_grid(.~dim,scales = "free",switch = "x") +
  labs(x="",y="",title = "Preferences") +
  scale_fill_manual(values = c("dodgerblue4","indianred4")) +
  scale_color_manual(values = c("dodgerblue4","indianred4")) +
  coord_cartesian(clip = "on",ylim = c(-2.5,2.5),expand = F) + 
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t,size = 12),
        plot.subtitle= element_text(family = fonte_t),
        title = element_text(family = fonte_t,size = 12),
        plot.caption = element_text(family = fonte_t),
        legend.position = "none",
        strip.text.y = element_blank(),
        strip.text.x =  element_text(size=11,hjust = .5,family = fonte_t),
        axis.text.x = element_blank()
  ) 

# Distancing evaluation
pref_isolaruim <-preferences %>% 
  dplyr::filter(ideologia>3,
                isolamento < 3
  ) %>%
  dplyr::select(rt1:rt8)

pref_isolabom <-preferences %>% 
  dplyr::filter(ideologia>3,
                isolamento > 3
  ) %>%
  dplyr::select(rt1:rt8)

importancia2 <-
  bind_cols(
    data.frame(isola_mal = conjoint::caImportance(y=pref_isolaruim,x=profiles)), 
    data.frame(isola_bem = conjoint::caImportance(y=pref_isolabom,x=profiles))
  ) %>% mutate(dim=c("Issue","Parties","Values","EconPol")) %>%
  pivot_longer(-dim)


barras_importancia2 <-
  importancia2 %>%
  ggplot(aes(x=dim,y=value,fill=name,color=name)) +
  geom_bar(color=NA,aes(alpha=paste(dim,name)),stat = "identity") +
  geom_text(fontface="bold",size=4,family = fonte_t,
            vjust=-.5,aes(label=paste0(round(value,1),"%"))) +
  facet_grid(name~dim,scales = "free",switch = "x",
             labeller = labeller(name = c("isola_mal"="Disapprove",
                                          "isola_bem"="Approve"))) +
  # facet_grid(cols = vars(name,dim),scales = "free",switch = "x",
  #            labeller = labeller(name = c("isola_mal"="Disapprove",
  #                                         "isola_bem"="Approve"))) +
  labs(x="",y="",title="B. Social Distancing Policy") +
  coord_cartesian(clip = "on",ylim = c(0,40),expand = F) + 
  # scale_fill_manual(values = c("dodgerblue4","indianred1","dodgerblue1","indianred1",
  #                              "dodgerblue1","indianred1","dodgerblue1","indianred4")) +
  scale_color_manual(values = c("dodgerblue4","indianred4")) +
  scale_fill_manual(values = c("dodgerblue4","indianred4")) +
  scale_alpha_manual(values = c(0.8,0.5,0.5,0.5,
                                0.5,0.5,0.5,0.8)) +
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        legend.position = "none",
        strip.text.y = element_text(size=12,face = "bold",hjust = .5,family = fonte_t),
        strip.text.x =  element_text(size=11,hjust = .5,family = fonte_t),
        
        plot.title= element_text(family = fonte_t,size=12),
        plot.subtitle= element_text(family = fonte_t),
        #  title = element_text(family = fonte_t),
        plot.caption = element_text(family = fonte_t),
        axis.text = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),)


m3 <- conjoint::caPartUtilities(y=pref_isolaruim,x=profiles,z=levelnames)

m4 <- conjoint::caPartUtilities(y=pref_isolabom,x=profiles,z=levelnames)

lab.graf.b <- data.frame(dim=c("EconPol",
                               "Issue",
                               "Values",
                               "Parties"),
                         valor_esq=rep(c(-2),4),
                         valencia_esq=c("+ State oriented",
                                        "+ Social policies",
                                        "+ Liberal",
                                        "+ Proparty"),
                         valor_dir=rep(c(2),4),
                         valencia_dir=c("+ Market oriented",
                                        "+ Anticorruption",
                                        "+ Conservative",
                                        "+ Antiparty"))



m3m4 <- m3 %>% data.frame() %>% mutate(Perfil="isola_mal") %>%
  bind_rows(m4 %>% data.frame() %>% mutate(Perfil="isola_bem")) %>%
  
  dplyr::select(-intercept) %>%
  pivot_longer(1:8) %>%
  mutate(
    dim = case_when(
      name %in% c("Corruption",
                  "Social") ~ "Issue",    
      name %in% c("Antiparty",
                  "Proparty") ~  "Parties", 
      name %in% c("Conservative",
                  "Liberal") ~  "Values", 
      name %in% c("Market_oriented",
                  "State_oriented") ~     "EconPol"
    ),
    ordem = case_when(
      name == "Corruption"~1,
      name == "Social"~2,
      name == "Antiparty"~1,
      name == "Proparty"~2,
      name == "Conservative"~1,
      name == "Liberal"~2,
      name == "Market_oriented"~1,
      name == "State_oriented"~2
    )
  ) %>%
  dplyr::filter(ordem==1) %>%
  left_join(lab.graf.b)

valencias_conjoint2 <-
  m3m4 %>% 
  #dplyr::filter(dim %in% c("Values")) %>%
  dplyr::filter(dim %in% c("Values","EconPol")) %>%
  ggplot(aes(x=name,y=value,color=Perfil)) +
  #  geom_jitter(alpha=.05) +
  stat_summary(fun = mean, 
               geom = "point",
               position = position_dodge(width = 0.4)) + 
  
  stat_summary(fun.data = mean_cl_boot,  
               geom = "errorbar", width = 0.4,
               position = position_dodge()) +
  geom_hline(yintercept = 0,linetype=2) +
  geom_text(aes(y=valor_esq,label=valencia_esq),
            color="black",family = fonte_t,
            size=3.5,check_overlap = T) +
  geom_text(aes(y=valor_dir,label=valencia_dir),
            color="black",family = fonte_t,
            size=3.5,check_overlap = T) +
  facet_grid(.~dim,scales = "free",switch = "x") +
  labs(x="",y="",title = "Preferences") +
  scale_fill_manual(values = c("dodgerblue4","indianred4")) +
  scale_color_manual(values = c("dodgerblue4","indianred4")) +
  coord_cartesian(clip = "on",ylim = c(-2.5,2.5),expand = F) + 
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t,size = 11),
        plot.subtitle= element_text(family = fonte_t),
        title = element_text(family = fonte_t,size = 11),
        plot.caption = element_text(family = fonte_t),
        legend.position = "none",
        strip.text.y = element_blank(),
        strip.text.x =  element_text(size=11,hjust = .5,family = fonte_t),
        axis.text.x = element_blank()
  ) 
# Entra fig2
avalia_bemvsmal_fig <- barras_importancia + valencias_conjoint + patchwork::plot_layout(widths = c(2,1.5))

avalia_bemvsmal_fig2 <- barras_importancia2 + valencias_conjoint2 + patchwork::plot_layout(widths = c(2,1.5)) 

barras_importancia + valencias_conjoint + barras_importancia2 + valencias_conjoint2 +
  patchwork::plot_layout(design = "
                         13
                         13
                         13
                         24
                         24") -> conj_comparison

ggsave("fig2.png",plot=conj_comparison,dpi=320,width = 20, height = 20, units = "cm")

# Regressions ----

# filtrando apenas direita
fit4 <- df %>%
  dplyr::filter(ideologia>3) %>%
  mutate(covid = factor(coron,
                        levels = c(1,2,3,4),
                        labels = c("livre",
                                   "leve",
                                   "grave",
                                   "morte")),
         preju_d = case_when(
           prejuizo %in% c("Nenhum\nprejuízo",
                           "Pequeno\nprejuízo",
                           "Médio\nprejuízo",
                           "Grande\nprejuízo") ~ "Parcial",
           prejuizo %in% c("Total\nprejuízo") ~ "Total"
         ),
         covid_n = as.numeric(covid),
         prejuizo = as.numeric(preju),
         isolamento = as.numeric(favor_isol),
         bolsonaro = as.numeric(trabbolso),
         governadores= as.numeric(trabgov),
         trat=as.factor(trat_unify),
         tempo=as.numeric(time)) %>%
  dplyr::select(isolamento,tempo,governadores,bolsonaro,
                preju_d,prejuizo,
                covid,covid_n,
                sexo,renda=renda_cat,idade=idade2,trabbolso
  ) %>%
  drop_na() %>% lm(formula = isolamento ~ covid*preju_d + sexo + renda + idade)


reg.df <- preferences_cargas %>% 
  dplyr::filter(ideologia>3) %>%
  mutate(voto_dummy = case_when(
    voto_bolsonaro_grupo == "Anti-Bolsonaro"~0,
    voto_bolsonaro_grupo == "Anti-left"~0,
    voto_bolsonaro_grupo == "Pro-Bolsonaro"~1 
  ),
  voto_dummy_alt = case_when(
    voto_bolsonaro_grupo == "Anti-Bolsonaro"~0,
    voto_bolsonaro_grupo == "Anti-left"~1,
    voto_bolsonaro_grupo == "Pro-Bolsonaro"~1 
  ))

flog = voto_dummy ~ 
  covid_n*Conservative +
  Market_oriented +
  Antiparty +
  Corruption +
  covid_n*econ_loss_d #+ evangelico

reg.log <- glm(family = "binomial",
      formula = flog, 
      data=reg.df)

# FIGURE 3 ----
             
pred_covid <- jtools::effect_plot(model=reg.log,pred=covid_n,interval = T) +
  scale_x_continuous("COVID exposure",
                     breaks = c(1,2,3,4),
                     labels = c("Free","Mild","Strong","Death")) +
  scale_y_continuous(labels = scales::percent,
                     "Probabilidade de voto",
                     limits = c(0,1),
                     breaks = c(0,.05,.1,.15,.20,.25,.30,.35,.5,.75,1))  + 
  ggtitle("Marginal Effects") +
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t),
        plot.subtitle= element_text(family = fonte_t),
        plot.caption = element_text(family = fonte_t),
        title = element_text(family = fonte_t),
        strip.text = element_text(family = fonte_t),
        panel.spacing=grid::unit(.5, "lines"),
        plot.margin = ggplot2::margin(4, 4, 4, 4))
  
pred_conserva<- jtools::effect_plot(model=reg.log,pred=Conservative,interval = T) +
  scale_x_continuous("Conservatism",
                     breaks = c(-2.5,0,2.5,5),
                     labels = c("Liberal","","Conservative","")) +
  scale_y_continuous(labels = scales::percent,
                     "Voting probability",
                     limits = c(0,1)) +
  theme_ipsum_mod +
  theme(axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t),
        plot.subtitle= element_text(family = fonte_t),
        plot.caption = element_text(family = fonte_t),
        title = element_text(family = fonte_t),
        strip.text = element_text(family = fonte_t),
        panel.spacing=grid::unit(.5, "lines"),
        plot.margin = ggplot2::margin(4, 4, 4, 4))


plot_reg <- jtools::plot_summs(reg.log,exp = T,
                               coefs=c( "COVID exposure" = "covid_n",
                                        "Economic Loss" = "econ_loss_d1",
                                        "Conservatism" = "Conservative",
                                        "Market orientation" = "Market_oriented",
                                        "Antipartism" = "Antiparty",
                                        "Anticorruption issue" = "Corruption"#,"evangelico","covid_n:Conservative","covid_n:econ_loss_d1"
                                        )
                               ) +
  scale_y_discrete(position = "left","") + 
  scale_x_continuous("(exp(b)-1)",
                     breaks = c(.75,1,1.25,1.75),
                     labels = c("-25%","0","+25%","+75%")) +
  ggtitle("Regression Model") +
  theme_ipsum_mod +
  theme(text = element_text(family = fonte_t),
        plot.title= element_text(family = fonte_t),
        plot.subtitle= element_text(family = fonte_t),
      #  title = element_text(family = fonte_t),
        plot.caption = element_text(family = fonte_t),
        strip.text = element_text(family = fonte_t),
        panel.spacing=grid::unit(.5, "lines"),
        plot.margin = ggplot2::margin(4, 4, 4, 4))

# Entra 
regressao2_plot <- plot_reg + pred_covid + pred_conserva + plot_layout(widths = c(2,1,1))

regressao2_plot
#write_rds(regressao2_plot,"regressao2_plot.rds")
ggsave("fig4.png",plot=regressao2_plot,dpi=320,width = 35, height = 15, units = "cm")

jtools::export_summs(reg.log,exp = T)


inter <- lm(#family = "binomial",
             formula = isolamento ~ 
               covid*econ_loss*Conservative, 
             data=reg.df)

sjPlot::plot_model(model=inter,type="int")


intera <- lm(#family = "binomial",
  formula = isolamento ~ 
    covid*econ_loss, 
  data=reg.df %>% dplyr::filter(ideologia>3))

p.int.b <- sjPlot::plot_model(model=intera,type="int") + #,mdrt.values = "meansd") + 
  scale_color_manual(labels=c("Partial","Total"),values = c("indianred3","dodgerblue3")) +
  scale_x_continuous(labels = c("None","Mild","Strong","Death")) +
  scale_y_continuous(limits=c(2,5)) +
  labs(title="Round 2: Predicted values and interaction",x="Exposure to COVID-19",y="Support for Social Distancing",
       color="Economic loss") +
  theme_ridges() + 
  theme(text = element_text(family=fonte_t),
        legend.position = "right")

p.int.a <- sjPlot::plot_model(fit4, type = "int") + 
  scale_color_manual(labels=c("Total","Partial"),values = c("dodgerblue3","indianred3")) +
  scale_x_continuous(labels = c("None","Mild","Strong","Death")) +
  scale_y_continuous(limits=c(2,5)) +
  labs(title="Round 1: Predicted values and interaction",x="Exposure to COVID-19",y="Support for Social Distancing",
       color="Economic loss") +
  theme_ridges() + 
  theme(text = element_text(family=fonte_t),
        legend.position = "none")


inter.plot <- p.int.a + p.int.b #+ plot_layout(guides='collect') &
  theme(legend.position='bottom')
ggsave("interaction.png",plot=inter.plot,dpi=320,width = 30, height = 15, units = "cm")
